<template>
    <div>
        <div class="search">
            <input  v-model='keyword' class="search-input" type="text" placeholder="输入城市">
        </div>
        <div class="search-content" ref='wrapper' v-show='keyword'>
            <ul class="search-result">
                <li class="search-result-item border-bottom" v-for='item in list' :key='item.id' @click="handleCityClick(item.name)" >{{item.name}}</li>
                <li class="search-result-item border-bottom" v-show='hasData' >没有找到匹配的数据</li>
            </ul>
        </div>
    </div>
</template>
<script>
import BScroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      timer: null,
      list: []
    }
  },
  computed: {
    hasData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      //   console.log(this.keyword)
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        let result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 ||
              value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  methods: {
    handleCityClick (city) {
      //   this.$store.dispatch('handleCityChange', city)
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  mounted () {
    const wrapper = this.$refs.wrapper
    this.scroll = new BScroll(wrapper)
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/variables.styl'
.search
    padding:0 .1rem
    height:.72rem
    background :$bgColor
    font-size:.24rem
    .search-input
        width:100%
        height:.62rem
        padding:0 .1rem
        box-sizing:border-box
        line-height :.62rem
        text-align :center
        color:#333
        border-radius:.06rem
.search-content
    position:absolute
    top:1.58rem
    left:0
    right:0
    bottom:0
    z-index:1
    background:#fff
    overflow :hidden
    .search-result
        .search-result-item
            padding-left:.2rem
            line-height :.44rem
</style>
